/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package stock.avanza;

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import misc.Helpers;

import com.gargoylesoftware.htmlunit.CookieManager;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.util.Cookie;

public class Login {

    private final WebClient client;

    public Login() {
        client = Helpers.createNewAndSilenceWebClient();
        login();

        Calendar nextTrigger = Calendar.getInstance();
        nextTrigger.set(Calendar.HOUR_OF_DAY, 8);
        if (Calendar.getInstance().get(Calendar.HOUR_OF_DAY) > 8) {
            nextTrigger.add(Calendar.DAY_OF_MONTH, 1);
        }
        new Timer().scheduleAtFixedRate(new TimerTask() {

            @Override
            public void run() {
                login();
            }
        }, new Date(nextTrigger.getTimeInMillis()), 86400000);

    }

    public void makeLoggedIn(WebClient client) {
        CookieManager manager = client.getCookieManager();
        manager.clearCookies();
        for (Cookie c : this.client.getCookieManager().getCookies()) {
            manager.addCookie(c);
        }
    }

    private void login() {
        System.out.println("Loggar in...");
        try {
            final HtmlPage p = client
                    .getPage("https://www.avanza.se/aza/login/login.jsp");

            Thread.sleep(5000);

            final HtmlForm loginFormElement = p.getFormByName("login");

            loginFormElement.getInputByName("username").setValueAttribute(
                    "atp10mla");
            loginFormElement.getInputByName("password").setValueAttribute(
                    "kattkatt1");
            loginFormElement.getInputByName("loginBtn").click();
        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("Failed to login, trying again in 10 secs...");
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
            }
            login();
        }
    }

}
